﻿using Common;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace FastAPI.Controllers
{
	[ApiController]
	[Route("KDNiao")]
	public class KDNiaoController : ControllerBase
	{
        private static string conn_wh = string.Empty;
        private static string conn_cs = string.Empty;

        private static string conn_xd = string.Empty;
        private static string kdnID = string.Empty;
        private static string kdnKey = string.Empty;

        static KDNiaoController()
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json");

            IConfigurationRoot config = builder.Build();
            conn_wh = config["MallDB_Conns:Wuhan"];
            conn_cs = config["MallDB_Conns:Changsha"];
            conn_xd = config["MallDB_Conns:Xingdao"];
            kdnID = config["KDNiao:EBusinessID"];
            kdnKey = config["KDNiao:AppKey"];
        }


        [Route("UpdateExpressInfo"), HttpPost]
        public async Task<string> UpdateExpressInfo(dynamic requestJson)
        {
			try
			{
               var postdata =  Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(requestJson.ToString());


                string dbcode = postdata.dbcode!=null?postdata.dbcode.ToString():"";
                string shippercode = postdata.shippercode != null?postdata.shippercode.ToString():"";
                string logisticnum = postdata.logisticnum != null?postdata.logisticnum.ToString():"";
                string customername = postdata.customername != null?postdata.customername.ToString():""; //收件手机号后四位

                if (string.IsNullOrEmpty(dbcode) || string.IsNullOrEmpty(dbcode) || string.IsNullOrEmpty(dbcode)) 
                {
                    return Newtonsoft.Json.JsonConvert.SerializeObject(new
                    {
                        success = false,
                        message=$@"参数缺失：dbcode:{dbcode}|shippercode:{shippercode}|logisticnum:{logisticnum}"
                    });
                }
                if (shippercode.ToLower() == "sf") {
                    if (string.IsNullOrWhiteSpace(customername)) {
                        return Newtonsoft.Json.JsonConvert.SerializeObject(new
                        {
                            success = false,
                            message = $@"参数缺失：customer:{customername}"
                        });
                    }
                }

                string shippercode2 = shippercode;
                if (shippercode == "JD7") 
                {
                    shippercode2 = "JD";
                }
                #region 调用快递鸟接口获取和更新物流信息
                string requestData = string.Empty;
                if (shippercode.ToLower() == "sf")
                {
                    requestData = "{ShipperCode:'" + shippercode2 + "',LogisticCode:'" + logisticnum + "',IsReturnRouteMap:1,CustomerName:'"+customername+"'}";

                }
                else { 
                    requestData = "{ShipperCode:'" + shippercode2 + "',LogisticCode:'" + logisticnum + "',IsReturnRouteMap:1}";
                }



                string jsondata = Newtonsoft.Json.JsonConvert.SerializeObject(new {
                    RequestData= HttpUtility.UrlEncode(requestData, Encoding.UTF8),
                    EBusinessID=int.Parse(kdnID),
                    RequestType=8003,
                    DataSign=KDNiaoEncrypt.encrypt(requestData,kdnKey, "UTF-8"),
                    DataType=2
                });

                Dictionary<string, string> param = new Dictionary<string, string>();
                param.Add("RequestData", HttpUtility.UrlEncode(requestData, Encoding.UTF8));
                param.Add("EBusinessID", kdnID);
                param.Add("RequestType", "8003");
                string dataSign = KDNiaoEncrypt.encrypt(requestData, kdnKey, "UTF-8");
                param.Add("DataSign", HttpUtility.UrlEncode(dataSign, Encoding.UTF8));
                param.Add("DataType", "2");
                StringBuilder paramStr = new StringBuilder();
                if (param != null && param.Count > 0)
                {
                    foreach (var p in param)
                    {
                        if (paramStr.Length > 0)
                        {
                            paramStr.Append("&");
                        }
                        paramStr.Append(p.Key);
                        paramStr.Append("=");
                        paramStr.Append(p.Value);
                    }
                }
                jsondata = paramStr.ToString();



                string kdnRes=await WebHelper.HttpPost("https://api.kdniao.com/Ebusiness/EbusinessOrderHandle.aspx",jsondata,null);

                KdnResp kr = Newtonsoft.Json.JsonConvert.DeserializeObject<KdnResp>(kdnRes);
                List<KdnTrace> traces = kr.Traces;
				foreach (KdnTrace item in traces)
				{
                    item.AcceptStation= KDNiaoEncrypt.ToUnicodeString(item.AcceptStation);
                }

                int logistics_status = int.Parse(kr.State);
                string logistics_content = Newtonsoft.Json.JsonConvert.SerializeObject(kr.Traces);

                logistics_content= logistics_content.Replace("\\\\","\\");

                string logistics_map_url = kr.RouteMapUrl;
                #endregion

                #region 更新数据库
                string connstr = string.Empty;
                switch (dbcode)
				{
                    case "wh":
                        connstr = conn_wh;
                        break;
                    case "cs":
                        connstr = conn_cs;
                        break;
                    case "xd":
                        connstr = conn_xd;
                        break;
                    default:
						break;
				}
                Dictionary<string, object> parameters = new Dictionary<string, object>();
                parameters.Add("@logistics_num", logisticnum);
                parameters.Add("@logistics_code", shippercode);
                parameters.Add("@logistics_content", logistics_content);
                parameters.Add("@logistics_map_url", logistics_map_url);

                MYSQLHelper.ExecNonQuery($@"update jbr_orders_sub_logistics set  logistics_status={logistics_status},logistics_content=@logistics_content,logistics_map_url=@logistics_map_url where logistics_num=@logistics_num and logistics_code=@logistics_code; ", connstr,parameters);


                #endregion



                return Newtonsoft.Json.JsonConvert.SerializeObject(new
                {
                    success = true
                });

            }
			catch (Exception ex)
			{
                return Newtonsoft.Json.JsonConvert.SerializeObject(new
                {
                    success = false,
                    message = ex.Message
                }) ;
			}
            
        }

    }

	 class KdnResp
	{
		public string State { get; set; }
		public List<KdnTrace> Traces { get; set; }
        public string RouteMapUrl { get; set; }

    }
    class KdnTrace
    {
        public string AcceptTime { get; set; }
        public string AcceptStation { get; set; }
        public string Remark { get; set; }
    }
}
